import {videoRootDir} from '@/utils/config.ts'
import {AccessRecord, Movie, MovieKey} from '@/data/Dream'
import {recordMovieAccessRecords, recordVideoAccessRecords} from '@/data/access_records.ts'
import router from '@/router'

export function gotoDreamVideo(movie: Movie) {
    recordMovieAccessRecords(getMovieKey(movie))
    router.push({
        path: '/dreamVideo', query: <any>getMovieIdObj(movie),
    })
}

export function getMovieIdObjByVideo(videoFileName: string): MovieKey {
    const regResult = videoFileName.match(/^(\d{4})\.(.+?)[.\-_—]/)
    const year = parseInt(regResult[1])
    const name = regResult[2]
    return {name, year}
}

export function getMovieIdObj(movie: Movie): MovieKey {
    const {name, year} = movie
    return {name, year}
}

export function getMovieKey(movie: Movie) {
    return `${movie.year}.${movie.name}`
}

// 电影图片下方显示的标题，名称.年
export function getMovieTitle(movie: Movie) {
    return `${movie.name}.${movie.year}`
}

export function calVideoPath(movie: Movie, videoFileName: string) {
    const star = movie.star ? `${movie.star}/` : ''
    const videoRelativePath = `${star}${movie.year}.${movie.name}`
    const movieDir = `${videoRootDir}/${videoRelativePath}`

    return `${movieDir}/${videoFileName}`
}

export function formatSeconds(seconds: number) {
    // 四舍五入取整
    seconds = Math.round(seconds)
    // 计算小时、分钟和秒
    const hrs = Math.floor(seconds / 3600)
    const mins = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60

    // 将小时、分钟和秒格式化为字符串
    const h = hrs.toString().padStart(2, '0')
    const m = mins.toString().padStart(2, '0')
    const s = secs.toString().padStart(2, '0')

    // 组合成最终的时间字符串
    return `${h}:${m}:${s}`
}

export function formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0'

    const k = 1024
    const sizes = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']

    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return (
        parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + sizes[i]
    )
}

export function arraysHaveSameElements<T>(a1: T[], a2: T[]) {
    return a1.length === a2.length && a1.every(e => a2.includes(e))
}

let shell: any;
({shell} = require('electron'));

export function openVideoDefault(movie: Movie, videoFileName: string,
                                 videoAccessRecords: Map<string, AccessRecord>)
{
    // const {exec} = require('child_process')
    // const cmd = `D:/PotPlayer/PotPlayerMini64.exe ${fileFullPath}`
    // exec(cmd)
    const videoFilePath = calVideoPath(movie, videoFileName)
    shell.openPath(videoFilePath)
    videoAccessRecords.set(videoFileName, recordVideoAccessRecords(videoFileName))
}
